<?php
namespace Kuoqi\Worker;

//socket的客户端操作
class Client{
	
	protected $client = null;
	public $server_address = '0.0.0.0';//链接地址
	public $server_port = '0';//端口号信息
	public $events = array(
		'message'=>null,//接收到信息的绑定
	);//链接事件发生器列表
    //加密秘钥
    protected $password = 'm81jtgrx0fs0ys0ezbkqbnj2kg';
    //加密数据偏移量
    protected $iv = '2n2jkcc3cah3x0ht';

    /**
     * 是否数据验证通过
     * @var bool
     * User kuoqi
     * Datetime 2022/3/29 18:43
     * Remark
     */
    protected $is_valied = true;

    /**
     * 异常信息
     * @var string
     * User kuoqi
     * Datetime 2022/3/29 18:50
     * Remark
     */
    protected $errmsg = '';

	public function __construct($addr,$port){
		$this->server_address = $addr;
		$this->server_port = $port;
	}

	public function on($onFuncname,$onEvent){
		if(in_array($onFuncname,array_keys($this->events))){
			$this->events[$onFuncname] = $onEvent;
		}else{
			$this->say('Socket Client Error: there is no Bind code with ['.$onFuncname.']');
		}
	}
	
	//链接服务端
	public function connect(){
        if(!$this->client){
            $this->client = @stream_socket_client("tcp://{$this->server_address}:{$this->server_port}/", $errno, $errstr);
            if (!$this->client)
                $this->is_valied = false;
                $this->errmsg = "KuoqiWorker Client : {$errno} : {$errstr}";
        }
    }
	
	//使用命令
	public function command($cmd){
		$data = \Kuoqi\Openssl::encode(serialize($cmd),'',$this->password,$this->iv,0);
		$rs = fwrite($this->client, $data);
		//$this->message();//执行获取消息的函数
		//$this->close();//执行关闭客户端
	}
	
	//发送数据
	public function send(){
		$proto = '';
		fwrite($this->client, $proto);
	}
	
	//获取数据
	public function message(){
		//读取服务端传来的数据
		if(isset($this->events['message'])){
			$rs = $this->events['message'];
			$msg = fread($this->client, 2048);
			$rs($msg,$this);
		}
	}
	
	//关闭客户端
	public function close(){
		//关闭客户端
		fclose($this->client);
		$this->client = null;
	}

    /**
     * 判定数据验签是否通过
     * @return bool
     * User kuoqi
     * Datetime 2022/3/29 18:54
     * Remark
     */
	public function isValied(){
	    return $this->is_valied;
    }

    /**
     * 获取错误信息
     * @return string
     * User kuoqi
     * Datetime 2022/3/29 18:53
     * Remark
     */
	public function getError(){
	    return $this->errmsg;
    }
}
